package com.pylc.testutil;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.database.search.TablesDependencyHelper;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.util.search.SearchException;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Lindsey
 */
public class XmlExportUtil {
    private static final String dbDriver = "com.mysql.jdbc.Driver";
    private static final String dbUrl = "jdbc:mysql://localhost:3306/pylc?useUnicode=true&characterEncoding=UTF-8";
    private static final String user = "root";
    private static final String password = "helpme";

    public static final String XML = ".xml";

    public static void main(String[] args) throws Exception {
        IDatabaseConnection connection = getDBConnection();

        exportFullDb(connection);

//        exportByQuery(connection, "SELECT * FROM area where id = 2", "store");
    }

    private static void exportWithDependentTables(IDatabaseConnection connection, String rootTable) throws SearchException, SQLException, IOException, DataSetException {
        // dependent tables database export: export table X and all tables that
        // have a PK which is a FK on X, in the right order for insertion
        String[] allDependentTables = TablesDependencyHelper.getAllDependentTables(connection, rootTable);
        IDataSet dependentDataSet = connection.createDataSet(allDependentTables);
        FlatXmlDataSet.write(dependentDataSet, new FileOutputStream(rootTable + XML));
    }

    private static void exportFullDb(IDatabaseConnection connection) throws SQLException, IOException, DataSetException {
        IDataSet fullDataSet = connection.createDataSet();
        FlatXmlDataSet.write(fullDataSet, new FileOutputStream("full.xml"));
    }


    private static void exportByQuery(IDatabaseConnection connection, String query, String table) throws SQLException, IOException, DataSetException {
        // partial database export
        QueryDataSet partialDataSet = new QueryDataSet(connection);
        partialDataSet.addTable(table, query);
        FlatXmlDataSet.write(partialDataSet, new FileOutputStream(table + XML));
    }

    private static IDatabaseConnection getDBConnection() throws ClassNotFoundException, SQLException {
        Class driverClass = Class.forName(dbDriver);
        Connection jdbcConnection = DriverManager.getConnection(dbUrl, user, password);
        return new DatabaseConnection(jdbcConnection);
    }
}